package com.geek.water.service.impl;


import com.geek.water.exception.HealthException;
import com.geek.water.service.FileStrategyService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

/**
 * @author chenmin
 * @desc 文件管理上下文
 * @date 2025/7/28
 */
@Service
public class FileUploadContext {

    //键 -> 策略在IOC容器中的beanName   值->策略
    private final Map<String, FileStrategyService> strategies;

    public FileUploadContext(Map<String, FileStrategyService> strategies) {
        this.strategies = strategies;
    }

    //上传
    public String upload(MultipartFile file, String provider) {
        try {
            System.out.println("开始上传文件，provider: " + provider);

            FileStrategyService uploadStrategy = strategies.get(provider);
            if (uploadStrategy == null) {
                System.err.println("未找到策略: " + provider);
                throw new HealthException("未知云服务运营商：" + provider);
            }

            System.out.println("找到策略: " + provider);
            String result = uploadStrategy.uploadFile(file);
            System.out.println("上传结果: " + result);
            return result;
        } catch (Exception e) {
            System.err.println("文件上传上下文异常: " + e.getMessage());
            e.printStackTrace();
            throw new HealthException("文件上传失败: " + e.getMessage());
        }
    }

    //删除
    public boolean delete(String url, String provider) {
        try {
            System.out.println("开始删除文件，provider: " + provider + ", url: " + url);

            FileStrategyService uploadStrategy = strategies.get(provider);
            if (uploadStrategy == null) {
                System.err.println("未找到策略: " + provider);
                throw new HealthException("未知云服务运营商：" + provider);
            }

            System.out.println("找到策略: " + provider);
            boolean result = uploadStrategy.deleteFile(url);
            System.out.println("删除结果: " + result);
            return result;
        } catch (Exception e) {
            System.err.println("文件删除上下文异常: " + e.getMessage());
            e.printStackTrace();
            throw new HealthException("文件删除失败: " + e.getMessage());
        }
    }
}
